<?php

/*
 * @author Ebrain Cedeno <ebraincedeno@gmail.com>
 */
class QuoteController extends Controller{
    
    public function actionGrid(){
        VeCms::AccessValidate(array("admin"=>array(0,1)));
        
        if (isset($_GET['del']) AND $_GET['del']== true){
            $this->validate = new TForm();
            TForm::addMessage("delete", "El registro se ha eliminado correctamente");
            $this->del= $_GET['del'];
        }
        else{
            $this->del=false;
        }
        
        $this->button_new_quote = new TButton("Nuevo Presupuesto");
        $this->button_new_quote->Width = 160;
        
        $js_rol = '$(location).attr("href","../quote/new");';
        
        $this->button_new_quote->onClick = $js_rol;
        $this->button_new_quote->OptionsAditional = array('style'=>array('font-weight:bold',
                                                                        'cursor:pointer',
                                                                        'border:1px solid gray',
                                                                        'background-image:url('.VeCms::getPathImage().VeCmsEnum::ICON_ADD.')',
                                                                        'background-position:left',
                                                                        'background-repeat: no-repeat',
                                                                        'background-position-x:5px',
                                                                        'text-align: right'));
        $offset = (isset($_GET['offset']))?$_GET['offset']:0;
        $quote = new quote();
        $quote->fields = "DISTINCT (number) as number,id_product,id_client,amount,price,date_quote,active";
        $quote->Offset = $offset;
        $quote->Limit = 10;
        
        // generando el grid para los presupuestos guardados
        
        $this->grid_quote = new TTable();
        $this->grid_quote->Id = "grid-quote";
        $this->grid_quote->Width = '100%';
        $this->grid_quote->Columns = 7;
        $this->grid_quote->Rows = $quote->Limit;
        $this->grid_quote->Headers = array("","Numero","Cliente","Fecha","","","");
        $this->grid_quote->WidthCell[0] = 25;
        $this->grid_quote->RowsAlign[0] = "center";
        $this->grid_quote->WidthCell[1] = 200;
        $this->grid_quote->WidthCell[3] = 200;
        $this->grid_quote->WidthCell[4] = 25;
        $this->grid_quote->WidthCell[5] = 25;
        $this->grid_quote->WidthCell[6] = 25;
        
        $collection_quote = $quote->findAll("active = :active GROUP BY number",array(":active"=>1));
        $count =1;
        foreach ($collection_quote as $key=>$object){
            
            $delete = new TImage();
            $delete->Src = VeCms::getPathImage().  VeCmsEnum::ICON_DELETE;
            $delete->onClick = 'if (confirm(\'Esta seguro que desea desactivar este presupuesto\')){
                    $(location).attr("href","delete?number='.$object->number.'");
                }';
            $delete->OptionsAditional['style'][]= 'cursor:pointer';
            
            $view = new TImage();
            $view->Src = VeCms::getPathImage().VeCmsEnum::ICON_VIEW;
            $view->onClick = '$(location).attr("href","view?number='.$object->number.'");';
            $view->OptionsAditional['style'][]='cursor:pointer';
            
            $update = new TImage();
            $update->Src = VeCms::getPathImage().  VeCmsEnum::ICON_EDIT;
            $update->OptionsAditional['style'][]="cursor:pointer";
            
            $this->grid_quote->Items[] = array($count,$object->number, $object->client->business_name ,date("d-m-Y",$object->date_quote),$view->show(),$update->show(),$delete->show());
            $count++;
        }
        
    }
    
    public function actionNew(){
        
        VeCms::AccessValidate(array("admin"=>array(0,1)));
        
        $quote = new quote();
        
        if (isset($_POST['guardar'])){
            $quote->setAttributes($_POST);
            $quote->id_product = 1;
            $quote->price = 1;
            $id_client = $quote->id_client;
            $quote->id_client = client::model()->find("business_name=:business_name",array(":business_name"=>$quote->id_client))->id_client;
            $quote->id_user = TSession::getSession('user')->id_user;
            $quote->date_quote = strtotime($quote->date_quote);
            
            if ($quote->validate()){
                if (isset($_POST['id_product']) and count($_POST['id_product']) > 0){
                    $register_perfect = false;
                    foreach ($_POST['id_product'] as $key=>$id_product){
                        $quote->id_product =$id_product;
                        $quote->price = $_POST['price'][$key];
                        $quote->amount = $_POST['amount_value'][$key];
                        
                        if ($quote->save()){
                            $register_perfect = true;
                        }
                        else{
                            $register_perfect = false;
                        }
                        
                    }
                    if ($register_perfect == true){
                        TForm::addMessage("guardado","Se realizo el registro correctamente");
                        $quote->id_client = $id_client;
                        $this->redirec(VeCms::createUrl("grid"),5);
                    }
                    else{
                        TForm::addMessageError("list_product", "Error al intentar registrar el presupuesto en el sistema");
                    }
                }
                else{
                    TForm::addMessageError("list_product", "No se agregaron productos para generar el presupuesto");
                }
            }
        }
        
        $this->form = new TForm();
        $this->form->Method = "POST";
        $this->form->Action = VeCms::createUrl("new");
        
        $this->link_back = new TLink("Regresar");
            $js_link = "parent.history.back(); 
                        return false; 
                        ";
            
        
        $this->link_back->onClick = $js_link;
        $this->link_back->OptionsAditional['style'][] = "color:#A9BCF5";
        $this->link_back->OptionsAditional['style'][] = "font-weight:bold";
        
        $this->number_label = new TLabel("Numero:");
        $this->number_label->OptionsAditional = array('style'=>array('font-weight:bold'));
        $this->number_entry = new TEdit();
        $this->number_entry->Width = 100;
        $this->number_entry->Name = 'number';
        $this->number_entry->Id = $this->number_entry->Name;
        $this->number_entry->Text = $quote->number;
        $this->number_entry->OptionsAditional['style'][] = 'border:1px solid black';
        
        $this->id_client_label = new TLabel("Cliente:");
        $this->id_client_label->OptionsAditional = array('style'=>array('font-weight:bold'));
        $this->id_client_entry = new TEdit();
        $this->id_client_entry->Name = 'id_client';
        $this->id_client_entry->Id = $this->id_client_entry->Name;
        $this->id_client_entry->Width = 200;
        $this->id_client_entry->Height = 25;
        $this->id_client_entry->Text = $quote->id_client;
        $this->id_client_entry->OptionsAditional['style'][] = 'border:1px solid black';
        
        $this->dialog = new TDialog();
        $this->dialog->Name = "client_dialog";
        $this->dialog->Id = $this->dialog->Name;
        $this->dialog->AutoOpen = 'false';
        $this->dialog->Title = "CLIENTES";
        $this->dialog->Width = 600;
        $this->dialog->Height = 400;
        
        $iframe = new TIframe();
        $iframe->Width = 578;
        $iframe->Height = 350;
        $iframe->Url = '../client/gridremote';
        $iframe->OptionsAditional['style'][]='border:none';
        $this->dialog->add($iframe->show());
        
        $this->image_search = new TImage();
        $this->image_search->Src = VeCms::getPathImage().VeCmsEnum::ICON_VIEW;
        $this->image_search->onClick = '$'.$this->dialog->Id.'.dialog("open");
                                        return false;';
        $this->image_search->OptionsAditional["style"][] = 'cursor:pointer;';
        
        $this->date_quote_label = new TLabel("Fecha:");
        $this->date_quote_label->OptionsAditional = array('style'=>array('font-weight:bold'));
        $this->date_quote_entry = new TDatePicker();
        $this->date_quote_entry->Name = "date_quote";
        $this->date_quote_entry->Id = $this->date_quote_entry->Name;
        $this->date_quote_entry->Width = 250;
        $this->date_quote_entry->Height = 25;
        $this->date_quote_entry->OptionsAditional['style'][] = 'border:1px solid black';
        
        $this->amount_label = new TLabel("Cantidad:");
        $this->amount_label->OptionsAditional = array('style'=>array('font-weight:bold'));
        $this->amount_entry = new TEdit();
        $this->amount_entry->Name = "amount";
        $this->amount_entry->Id = $this->amount_entry->Name;
        $this->amount_entry->Width = 200;
        $this->amount_entry->Height = 25;
        $this->amount_entry->Text = $quote->amount;
        $this->amount_entry->KeyPress = '
                var tecla = document.all ? tecla = event.keyCode : tecla = event.which;
                return ((tecla > 47 && tecla < 58));
                ';
        $this->amount_entry->OptionsAditional['style'][] = 'border:1px solid black';
        
        
        $this->dialog_product = new TDialog();
        $this->dialog_product->Name = "product_dialog";
        $this->dialog_product->Id = $this->dialog_product->Name;
        $this->dialog_product->AutoOpen = 'false';
        $this->dialog_product->Title = "PRODUCTOS";
        $this->dialog_product->Width = 600;
        $this->dialog_product->Height = 400;
        
        $iframe_product =new TIframe();
        $iframe_product->Name = "popup_product";
        $iframe_product->Id = $iframe_product->Name;
        $iframe_product->Url = '../product/gridremote';
        $iframe_product->Width = 578;
        $iframe_product->Height = 350;
        $this->dialog_product->add($iframe_product->show());
        
        
        $this->button_add_producto = new TButton("Agregar Producto");
        $this->button_add_producto->Name = "add_button";
        $this->button_add_producto->Type = "button";
        $this->button_add_producto->Id = $this->button_add_producto->Name;
        $this->button_add_producto->onClick = '$'.$this->dialog_product->Id.'.dialog("open");';
        $this->button_add_producto->Width = 145;
        $this->button_add_producto->OptionsAditional = array('style'=>array('font-weight:bold',
                                                                        'cursor:pointer',
                                                                        'border:1px solid gray',
                                                                        'background-image:url('.VeCms::getPathImage().VeCmsEnum::ICON_ADD.')',
                                                                        'background-position:left',
                                                                        'background-repeat: no-repeat',
                                                                        'background-position-x:5px',
                                                                        'text-align: right'));
        
        
        
        $this->scrolled_list_add_product = new TScrolledWidget();
        $this->scrolled_list_add_product->Name = 'scrolled_add_poduct';
        $this->scrolled_list_add_product->Id = $this->scrolled_list_add_product->Name;
        $this->scrolled_list_add_product->Width = 670;
        $this->scrolled_list_add_product->Height = 200;
        
        //base ttable dinamic
        
        $grid_dinamic = new TTable();
        $grid_dinamic->Id = "grid-dinamic";
        $grid_dinamic->Columns = 5;
        $grid_dinamic->Rows = 1;
        $grid_dinamic->Width = '100%';
        $grid_dinamic->ShowFooter = false;
        $grid_dinamic->Headers = array("","Descripcion","Cantidad","Precio Unit.","Total");
        
        
        if (isset($_POST['id_product'])){
            
            $grid_dinamic->Rows = count($_POST['id_product']);
            $grid_dinamic->RowsAlign[0]="center";
            $counter = 1;
            foreach ($_POST['id_product'] as $key=>$id_product){
                
                $object_product = product::model()->find("id_product=:id_product",array(":id_product"=>$id_product));
                
                //generando el link de eliminar
                
                $delete = new TImage();
                $delete->Src = VeCms::getPathImage().  VeCmsEnum::ICON_DELETE;
                $delete->onClick = "delete_product('".$counter."')";
                $delete->OptionsAditional['style'][] = 'cursor:pointer';
                
                $edit_id_product = new TEdit();
                $edit_id_product->Name = "id_product[]";
                $edit_id_product->Id = $edit_id_product->Name;
                $edit_id_product->Text = $id_product;
                $edit_id_product->IsHidden = true;

                $edit_price = new TEdit();
                $edit_price->Name = "price[]";
                $edit_price->Id = $edit_price->Name;
                $edit_price->Text = $_POST['price'][$key];
                $edit_price->IsHidden = true;

                $edit_amount = new TEdit();
                $edit_amount->Name = "amount_value[]";
                $edit_amount->Id = $edit_price->Name;
                $edit_amount->Text = $_POST['amount_value'][$key];
                $edit_amount->IsHidden = true;
                
                $grid_dinamic->Items[]=array($delete->show(),$edit_id_product->show().$object_product->short_description,$edit_amount->show().(string)$edit_amount->Text,$edit_price->show().$edit_price->Text,($edit_amount->Text * $edit_price->Text));
                $grid_dinamic->IdRows[]= 'id_row_'.$counter;
                $counter++;
            }
        }
                
        $this->scrolled_list_add_product->add($grid_dinamic->show());
        
        $this->button_guardar = new TButton("Guardar");
        $this->button_guardar->Name = "guardar";
        $this->button_guardar->Id = $this->button_guardar->Name;
        $this->button_guardar->OptionsAditional['style'][] = 'font-weight:bold';
        $this->button_guardar->OptionsAditional['style'][] = 'cursor:pointer';
        
        
        
    }
    
    public function actionUpdate(){
        VeCms::AccessValidate(array("admin"=>array(0,1)));
    }
    
    public function actionDelete(){
        VeCms::AccessValidate(array("admin"=>array(0,1)));
        
        if (isset($_GET['number'])){
            $quote = quote::model()->findAll("number=:number",array(":number"=>$_GET['number']));
            $valid = false;
            foreach ($quote as $key=>$quote_object){
                $quote_object->active = 0;
                
                if ($quote_object->update()){
                    $valid = true;
                }
                else{
                    $valid = false;
                }
                
                if ($valid == true){
                    $this->redirec(VeCms::createUrl("grid"),0,array('del'=>true));
                }
                
            }
        }
        
    }
    
    public function actionView(){
        VeCms::AccessValidate(array("admin"=>array(0,1)));
    }
    
    
}
?>
